<?php

namespace app\admin\controller\stat;


use app\admin\model\hotel\Hotel;
use app\admin\model\hotel\HotelOrder;
use app\common\controller\Backend;


/**
 * 表格联动
 * 点击左侧日志列表，右侧的表格数据会显示指定管理员的日志列表
 * @icon fa fa-table
 */
class Rank extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['table1', 'table2','index'];

    public function _initialize()
    {
        parent::_initialize();

        //$this->model = model('\app\common\model\AdminWage');
    }


    public function index()
    {

        if ($this->request->isPost()) {

            $date = $this->request->post('date', '');

            $cityData = $this->getData($date);

            $statistics = [
                'list'=> $cityData['list']
            ];

            $this->success('', '', $statistics);

        }
        $data = $this->getData();


        $this->assign('list',$data['list']);

        $year = $this->getYearList('2024',2060);
        $this->assign('year',$year);
        return $this->view->fetch();
    }


    function getYearList($startYear, $endYear) {
        $years = range($startYear, $endYear);
        return $years;
    }
    public function getData($date='')
    {

        if ($date) {
            list($start, $end) = explode(' - ', $date);

            $starttime = $start;
            $endtime = $end;
        } else {
            /*$starttime = \fast\Date::unixtime('day', 0, 'begin','2022');
            $endtime = \fast\Date::unixtime('day', 0, 'end');
            $starttime = date('Y-m-d H:i',$starttime);
            $endtime = date('Y-m-d H:i',$endtime);*/
        }

        $hotel_list = collection(Hotel::field('hotel_id,hotel_name')->select())->toArray();


        foreach ($hotel_list as $k=>$v){
            if ($date){
                $count = HotelOrder::where('pay_status',1)
                    ->where('hotel_id',$v['hotel_id'])
                    ->whereTime('pay_time','between',[$starttime,$endtime])
                    ->count();
                $money = HotelOrder::where('pay_status',1)
                    ->where('hotel_id',$v['hotel_id'])
                    ->whereTime('pay_time','between',[$starttime,$endtime])
                    ->sum('pay_money');
            } else {
                $count = HotelOrder::where('pay_status',1)
                    ->where('hotel_id',$v['hotel_id'])
                    ->count();
                $money = HotelOrder::where('pay_status',1)
                    ->where('hotel_id',$v['hotel_id'])
                    ->sum('pay_money');
            }
            $hotel_list[$k]['count'] = $count;
            $hotel_list[$k]['money'] = $money;
        }
        //dump($hotel_list);die;
        array_multisort(array_column($hotel_list, 'money'), SORT_DESC, $hotel_list);

        return [
            'list'=>$hotel_list
        ];

    }


}